<?php
/**
 * TilesComponent. 
 * Used to create image from merging some image.
 * 
 * @author tuanlq@lifetimetech.vn
 */

App::uses('Component', 'Controller');
App::uses('Folder', 'Utility');

class TilesComponent extends Component {
	
	public function buildImage($destination = null, $source = array(), $level = null, $size = null, $separator = null) {
		if (!is_dir($destination)) {
			$Folder = new Folder();
			$Folder->create($destination, 777);
		}

		$dest = $destination . DS . 'res.jpg';
		$im = imagecreatetruecolor(635, 635);
		$white = imagecolorallocate($im, 255, 255, 255);
		
		// Draw a white rectangle
		imagefilledrectangle($im, 10, 10, 625, 625, $white);
		//$im = imagecreate(700, 700);
		//imagecolorallocate($im, 255, 255, 255);
		
// 		$white = imagecolorallocate($im, 255, 255, 255);
		
// 		// Draw a white rectangle
// 		imagefilledrectangle($im, 10, 10, 690, 690, $white);
		
		imagejpeg($im, $dest);
		
		$dest = imagecreatefromjpeg($destination . DS . 'res.jpg');
		
		$photoFrame = $destination . DS . 'res.jpg';
		
		//$border = imagecreatefrompng(WWW_ROOT . 'img' . DS . 'border.png');
		$border = imagecreatefrompng(WWW_ROOT . 'img' . DS . 'border.png');
		imagesavealpha($border, true);
		imagealphablending($border, true);
		
		$imgSource = array();
		$source = array_slice($source, 5, 16);
		
		$index = 0;
		foreach ($source as $sr) {
			$index += 1;
			$ims = imagecreatefromjpeg($sr);
			imagecopy($ims, $border, 0, 0, 0, 0, 150, 150);
			$imgSource[$index] = $ims;
		}
		
		$index = 0;
		for ($i = 0; $i <= 450; $i += 150) {
			for ($j = 0; $j <= 450; $j += 150) {
				$index += 1;
				$x = $j + (($j / 150) + 1) * 5;
				$y = $i + (($i / 159) + 1) * 5;
				imagecopymerge($dest, $imgSource[$index], $x, $y, 0, 0, 150, 150, 100);
			}
		}
		
		imagejpeg($dest, $photoFrame);
	}
}